import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, FlatList, PixelRatio } from "react-native";
import { GLOBAL } from '../../../config/global';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { Common } from '../../../component/common/Common.js';
import { style } from '../../../theme/style';
import { PriceTypeUI } from '../../../component/ui/PriceTypeUI';
import { CommonDialog } from '../../../components/common/Dialog';
import ToastUtil from '../../../utils/toast';
import { ProgressModal } from '../../../components/common/ProgressModal';
import MethodUtil from '../../../utils/MethodUtil';
import Utils from '../../../utils/utils';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
const scale = GLOBAL.SCALE;

export class ClinchRecord extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let { listData } = navigation.state.params || {};
    return {
      headerTitle: '成交记录',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('OfferApproveDetail', { ...listData }); }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    let { bidPackageId, bizModel, winRule, salesType } = props.navigation.state.params || {};
    console.log('props.navigation.state.params', props.navigation.state.params)
    this.state = {
      status: 'loading',
      refreshIcon: false,
      modalVisible: false,
      listData: [],
      message: '',// 申请原因
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '审批流',
        rowDataList: [],
        status: 'data',
        refreshIcon: false,
      },
    }
    this.bizModel = bizModel;
    this.winRule = winRule;
    this.salesType = salesType;
    this.pageParams = {
      bidPackageId,
      pageNo: 1,
      pageSize: 10
    }
  }

  componentWillMount() {
    this._initPage();
  }

  _initPage = async () => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    let res = null;
    if (this.bizModel === 'Z') {
      if (this.winRule == 'ALL') {
        res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_MAKE_LIST), this.pageParams);
      }
      else {
        res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_NOMAKE_LIST), this.pageParams);
      }
    }
    else {
      res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_NOMAKE_LIST), this.pageParams);
    }
    console.log('res', res);
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res : this.state.listData.concat(res),
        refreshIcon: false,
      })
    } else {
      this.setState({
        status: 'error',
        refreshIcon: false,
      })
    }
  }
  // 下拉刷新
  _refresh = () => {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this._initPage();
  }

  // 刷新
  _reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this._initPage();
  }

  // 加载更多
  _loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this._initPage();
    }
  }

  // 查看审批流
  _getCheckApprove = async (data) => {
    let { applyId, processInstanceId, corpId } = data || {};
    //查询审批节点AUDIT_QUERY_COMPANY
    let params = {
      bizId: applyId,
      bizObjType: 'BID_BARGAIN',
      processInstanceId,
      corpId,
    }
    let responseData = await HTTP.GET(API_GENERATE(API.APPROVAL_NODE), params);
    console.log('responseData', responseData)
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批流';
    lightBoxData.rowDataList = responseData;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }

  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }

  //撤回
  _withdraw = async (data) => {
    let { applyId } = data || {};
    let responseData = await HTTP.POST(API_GENERATE(API.PACKAGE_CLINCH_WITHDRAW), { applyId });
    console.log('responseData', responseData);
    if (responseData) {
      ToastUtil.showSuccess('撤回成功').then(() => {
        this._reloadPage();
      })
    }
  }
  _goDetail = (applyId) => {
    if (this.bizModel === 'Z') {
      this.props.navigation.navigate('PackOfferSituation', {
        bidPackageId: this.pageParams.bidPackageId,
        applyId,
        winRule: this.winRule === 'ALL' ? 'ALL' : 'SINGLE',
        salesType: this.salesType,
        type: 'RECORD'
      })
    } else { // 多伦
      this.props.navigation.push('OfferSituation', {
        bidPackageId: this.pageParams.bidPackageId,
        salesType: this.salesType,
        bizModel: this.bizModel,
        applyId,
      })
    }




  }
  //一条数据
  _renderListItem = (data) => {
    let { applyId, createTime, authTypeName, comments, bidPackageName, authStatusName, makeVTOList, entQty, purchaseAmt, competQuantity, canRevokeFlag } = data.item || {}
    return <TouchableOpacity style={styles.box}
      onPress={() => {
        this._goDetail(applyId)
      }}
    >
      <View style={[styles.head, styles.headMr]}>
        <Text style={styles.headText}>{applyId}</Text>
        <Text style={styles.headText}>{createTime}</Text>
      </View>
      <View style={styles.card}>
        <View style={[styles.head, styles.cardHead]}>
          <Text style={[styles.headText, styles.textBold, { flexWrap: 'wrap', width: '70%' }]}>{bidPackageName}</Text>
          <TouchableOpacity style={styles.approval} onPress={() => { this._getCheckApprove(data.item) }}>
            <Text style={[styles.headText, styles.textThemeColor]}>{authStatusName}</Text>
          </TouchableOpacity>
        </View>
        {
          this.bizModel === 'Z' && this.winRule === 'ALL' ? <View style={styles.billInfoWrap}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Text style={styles.commonText}>本次申请企业</Text>
              <Text style={styles.commonText}>本次申请总额</Text>
              <Text style={styles.commonText}>本次申请总量</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'flex-start', paddingTop: 8 * scale }}>
              <Text style={styles.commonText}>{entQty || '-'}</Text>
              <Text style={styles.commonText}>{'¥' + MethodUtil.toThousands(purchaseAmt || 0, 2) || '-'}</Text>
              <Text style={styles.commonText}>{competQuantity ? competQuantity + '吨' : '-'}</Text>
            </View>
          </View> : makeVTOList && makeVTOList.map((item, index) => {
            let { chineseName, competQuantity, orderCount, price, udPrice, purchaseQty, priceType } = item || {};
            return <View style={styles.cardBoxy} key={index}>
              <Text style={[styles.title, styles.textBold]}>{Utils.isEmpty(chineseName) ? '-' : chineseName}</Text>
              <View style={styles.cardBoxyRow}>
                <View style={styles.flexLeft}>
                  <Text style={[styles.textActive, styles.textBold]}>数量 {Utils.isEmpty(purchaseQty) ? '-' : purchaseQty}吨</Text>
                </View>
                <View style={styles.flexRight}>
                  <Text style={[styles.textActive, styles.textBold]}>¥{(priceType == 2 ? udPrice : price)} 元/吨</Text>
                  <PriceTypeUI data={{ priceType }} />
                </View>
              </View>
              <View style={styles.cardBoxyRow}>
                <View style={styles.flexLeft}>
                  <Text style={[styles.textActive, styles.textBold]}>申请量 {Utils.isEmpty(competQuantity) ? '-' : competQuantity}吨</Text>
                </View>
                <View style={styles.flexRight}>
                  <Text style={[styles.textActive, styles.textBold]}>申请意向 {Utils.isEmpty(orderCount) ? '-' : orderCount}条</Text>
                </View>
              </View>
            </View>
          })
        }
        <View style={[styles.cardFoot, styles.head]}>
          <View style={styles.cardFootRow}>
            <Text style={styles.headText}>申请类型: </Text>
            <Text style={styles.headText}>{authTypeName}</Text>
            {comments ?
              <TouchableOpacity style={styles.cardWhyBox} onPress={() => { this.setState({ modalVisible: true, message: comments }) }}>
                <Text style={[styles.textThemeColor, styles.cardWhy]}>申请原因</Text>
              </TouchableOpacity>
              : null
            }
          </View>
          {
            canRevokeFlag === 'Y' ? <TouchableOpacity style={styles.cancel} onPress={() => { this._withdraw(data.item) }}>
              <Text style={styles.cancelText}>撤回</Text>
            </TouchableOpacity> : null
          }
        </View>
      </View>
    </TouchableOpacity>
  }



  render() {
    let { modalVisible, listData, refreshIcon, message, lightBoxData, status } = this.state;
    return (
      <View style={styles.container}>
        {
          status == 'data' ? (
            <View style={{ flex: 1 }}>
              <FlatList
                data={listData}
                renderItem={this._renderListItem}
                refreshing={refreshIcon}
                onRefresh={() => { this._refresh() }}
                onEndReachedThreshold={0.1}
                onEndReached={() => { this._loadMore() }}
              />
            </View>
          ) : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无数据" onErrorPress={this._reloadPage} />) : null
        }
        <CommonDialog modalVisible={modalVisible} title={'申请原因'} text={message} onClosePress={() => { this.setState({ modalVisible: false }) }} />
        <ProgressModal {...lightBoxData} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  box: {
    marginHorizontal: 20 * scale,
    marginTop: 10 * scale
  },
  head: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  headMr: {
    paddingVertical: 10 * scale
  },
  headText: {
    fontSize: 12 * scale,
    color: '#060606'
  },
  card: {
    backgroundColor: style.color.white,
    paddingVertical: 5 * scale,
    paddingHorizontal: 10 * scale
  },
  cardHead: {
    paddingVertical: 10 * scale,
    borderColor: "#E3E7F0",
    borderBottomWidth: 1 / PixelRatio.get(),
    flexDirection: 'row',
    alignItems: 'center'
  },
  textBold: {
    fontWeight: 'bold'
  },
  textThemeColor: {
    color: style.color.themeColor
  },
  cardFootRow: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  cardWhy: {
    fontSize: 12 * scale,
  },
  cardWhyBox: {
    paddingHorizontal: 15 * scale,
    paddingVertical: 5 * scale
  },
  cardFoot: {
    paddingVertical: 10 * scale,
    borderColor: "#E3E7F0",
    borderTopWidth: 1 / PixelRatio.get(),
  },
  title: {
    fontSize: 14 * scale,
    color: '#000',
    marginBottom: 12 * scale
  },
  cardBoxy: {
    paddingVertical: 10 * scale
  },
  cardBoxyRow: {
    flex: 1,
    flexDirection: 'row',
    paddingVertical: 5 * scale
  },
  flexLeft: {
    width: '40%',
    flexDirection: 'row'
  },
  flexRight: {
    width: '60%',
    flexDirection: 'row'
  },
  textActive: {
    fontSize: 12 * scale,
    color: '#000'
  },
  cancel: {
    backgroundColor: '#FA6400',
    paddingVertical: 8 * scale,
    paddingHorizontal: 20 * scale,
    borderRadius: 20 * scale
  },
  cancelText: {
    color: style.color.white,
    fontSize: 12 * scale
  },
  approval: {
    borderColor: style.color.themeColor,
    borderWidth: 1 / PixelRatio.get(),
    paddingHorizontal: 6 * scale,
    height: 22 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 20 * scale
  },
  billInfoWrap: {
    flexDirection: 'column',
    alignItems: 'flex-start',
    justifyContent: 'flex-start',
    paddingLeft: 14 * scale,
    paddingRight: 14 * scale,
    paddingVertical: 20 * scale,
  },
  commonText: {
    flex: 1,
    fontSize: 11 * scale,
    color: '#0C0C0D',
    textAlign: 'center'
  },

})